<template>
  <div class="image-upload">
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      :action="uploadAction"
      :headers="uploadHeaders"
      :before-upload="beforeUpload"
      :on-success="onUploadSuccess"
      :on-error="onUploadError"
      :show-file-list="false"
      :auto-upload="true"
      name="image"
      accept="image/*"
    >
      <template #trigger>
        <el-button 
          type="primary" 
          :icon="Upload" 
          :loading="uploading"
          size="small"
        >
          {{ uploading ? '上传中...' : '插入图片' }}
        </el-button>
      </template>
    </el-upload>

    <!-- 上传进度提示 -->
    <el-dialog
      v-model="showProgress"
      title="图片上传"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="upload-progress">
        <el-progress
          :percentage="uploadProgress"
          :status="uploadStatus"
          :stroke-width="8"
        />
        <p class="progress-text">{{ progressText }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, type UploadInstance, type UploadProps } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import { uploadService } from '../services/upload'
import { useAuthStore } from '../stores/auth'

interface Props {
  onSuccess?: (url: string) => void
  onError?: (error: string) => void
}

const props = defineProps<Props>()

const authStore = useAuthStore()
const uploadRef = ref<UploadInstance>()
const uploading = ref(false)
const showProgress = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref<'success' | 'exception' | 'warning' | ''>('')

// 上传地址和请求头
const uploadAction = computed(() => {
  // 根据环境确定上传地址
  if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
    return 'http://127.0.0.1:3000/api/upload/image'
  }
  // 生产环境使用相对路径
  return '/api/upload/image'
})

const uploadHeaders = computed(() => {
  const token = authStore.getToken()
  return token ? { Authorization: `Bearer ${token}` } : {}
})

// 进度文本
const progressText = computed(() => {
  if (uploadStatus.value === 'success') {
    return '上传成功！'
  } else if (uploadStatus.value === 'exception') {
    return '上传失败！'
  } else if (uploading.value) {
    return `上传中... ${uploadProgress.value}%`
  }
  return '准备上传...'
})

// 上传前验证
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const validation = uploadService.validateImageFile(file)
  
  if (!validation.valid) {
    ElMessage.error(validation.error || '文件验证失败')
    return false
  }

  // 显示进度对话框
  uploading.value = true
  showProgress.value = true
  uploadProgress.value = 0
  uploadStatus.value = ''

  return true
}

// 上传成功回调
const onUploadSuccess = (response: any) => {
  uploading.value = false
  uploadProgress.value = 100
  uploadStatus.value = 'success'

  setTimeout(() => {
    showProgress.value = false
  }, 1500)

  if (response.success && response.data) {
    const imageUrl = uploadService.getImageUrl(response.data.url)
    ElMessage.success('图片上传成功')
    props.onSuccess?.(imageUrl)
  } else {
    ElMessage.error(response.message || '上传失败')
    props.onError?.(response.message || '上传失败')
  }
}

// 上传失败回调
const onUploadError = (error: any) => {
  uploading.value = false
  uploadProgress.value = 0
  uploadStatus.value = 'exception'

  setTimeout(() => {
    showProgress.value = false
  }, 2000)

  const errorMessage = error.message || '图片上传失败'
  ElMessage.error(errorMessage)
  props.onError?.(errorMessage)
}

// 手动触发上传
const triggerUpload = () => {
  uploadRef.value?.clearFiles()
  // 直接点击内部输入元素
  const inputElement = uploadRef.value?.$el?.querySelector('input[type="file"]')
  inputElement?.click()
}

// 暴露方法给父组件
defineExpose({
  triggerUpload
})
</script>

<style scoped>
.image-upload {
  display: inline-block;
}

.upload-demo {
  display: inline-block;
}

.upload-progress {
  text-align: center;
  padding: 20px 0;
}

.progress-text {
  margin-top: 16px;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .upload-progress {
    padding: 15px 0;
  }
  
  .progress-text {
    font-size: 13px;
  }
}
</style>